package com.tansun.easycare.rule.utils;

import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import com.tansun.easycare.rule.exception.BizException;
import org.hibernate.validator.HibernateValidator;

public class ValidationUtils {

    /**
     * 使用hibernate的注解来进行验证
     *
     */
    private static Validator validator = Validation
            .byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();

    /**
     * 支持list和Object参数校验，采用的是hibernate中的校验 linjintian
     * @param obj
     * @param <T>
     */
    public static <T> void validate(T obj) {
        if(obj instanceof List){
            List list = (List)obj;
            if(list != null && list.size()>0){
                for(Object object : list){
                    Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
                    if(constraintViolations.size()>0){
                        throw new BizException(String.format("参数校验失败:%s", constraintViolations.iterator().next().getMessage()));
                    }
                }
            }
        }else{
            Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
            if (constraintViolations.size() > 0) {
                throw new RuntimeException(String.format("参数校验失败:%s", constraintViolations.iterator().next().getMessage()));
            }
        }
    }
}
